<template>
  <div class="learning-data-analysis">
    <!-- 标题区域 -->
    <div class="header-container">
      <h2 class="main-title">用户题目收藏列表</h2>
      <div class="title-line"></div>
    </div>
    
    <!-- 顶部筛选栏 -->
    <el-card class="filter-card">
      <div class="filter-bar">
        <!-- 用户搜索区域 -->
        <div class="search-section">
          <div class="user-search">
            <el-input 
              v-model="searchInput" 
              placeholder="请输入用户名" 
              clearable
              @clear="clearSearch"
              @keyup.enter="handleSearch"
              style="width: 300px">
              <template #prepend>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
            <el-button 
              type="primary" 
              class="custom-primary-button"
              @click="handleSearch"
              :loading="isLoading">
              搜索用户
            </el-button>
            <el-button 
              class="custom-reset-button"
              @click="clearSearch">
              清除搜索
            </el-button>
          </div>
          
          <div v-if="selectedUser" class="user-details">
            <div class="user-id">用户ID: <span class="highlight">{{ selectedUser.userId }}</span></div>
            <div class="user-name">用户名: <span class="highlight">{{ selectedUser.username }}</span></div>
          </div>
        </div>
        
        <!-- 科目筛选 -->
        <div class="filter-section">
          <div class="subject-filter">
            <div class="filter-label">科目:</div>
            <el-select 
              v-model="selectedSubject" 
              placeholder="选择科目" 
              style="width: 200px">
              <el-option 
                v-for="subject in subjects" 
                :key="subject.id" 
                :label="subject.name" 
                :value="subject.id" />
            </el-select>
          </div>
          <el-button type="primary" class="custom-primary-button" @click="handleConfirmFilter">确认筛选</el-button>
        </div>
      </div>
    </el-card>
  
    <!-- 收藏题目列表 -->
    <el-card class="collected-questions-card">
      <div class="overview-header">
        <div class="header-gradient"></div>
        <h3>收藏题目列表</h3>
      </div>
      <div class="collected-questions-list">
        <div v-if="collectedQuestions.length === 0" class="no-data">
          <el-icon><Collection /></el-icon>
          <p>暂无收藏题目</p>
        </div>
        
        <div v-else>
          <div 
            class="collection-item" 
            v-for="item in collectedQuestions" 
            :key="item.questionId"
            @click="viewQuestionDetail(item.questionId)">
            <div class="question-content">
              <div class="question-title">
                <span class="question-id">#{{ item.questionId }}</span>
                <span v-html="truncateContent(item.content)"></span>
              </div>
              <div class="question-meta">
                <el-tag :type="getQuestionTypeTag(item.questionType)" size="small">
                  {{ formatQuestionType(item.questionType) }}
                </el-tag>
                <span class="subject">{{ item.subjectName }}</span>
                <span class="chapter">{{ item.chapterName }}</span>
              </div>
              <div class="question-details">
                <div class="knowledge">
                  <el-icon><Connection /></el-icon>
                  知识点: {{ item.pointNames }}
                </div>
                <div class="exam-type">
                  <el-icon><Tickets /></el-icon>
                  试卷类型: {{ item.examType }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 分页控件 -->
      <div class="pagination" v-if="totalCollectedQuestions > 0">
        <div class="total-items">总共 {{ totalCollectedQuestions }} 条</div>
        <el-pagination
          background
          layout="sizes, prev, pager, next, jumper"
          :total="totalCollectedQuestions"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          @current-change="loadCollectedQuestions"
          @size-change="handleSizeChange"
        />
        <div class="page-info">
          第{{ currentPage }}页/共{{ Math.ceil(totalCollectedQuestions / pageSize) }}页
        </div>
      </div>
    </el-card>

    <!-- 收藏题目详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="收藏题目详情" 
      width="70%">
      <div v-if="currentQuestionDetail" class="question-detail">
        <div class="detail-header">
          <h3>{{ currentQuestionDetail.subjectName }} - {{ currentQuestionDetail.chapterName }}</h3>
          <div class="meta-info">
            <el-tag :type="getQuestionTypeTag(currentQuestionDetail.questionType)" size="large">
              {{ formatQuestionType(currentQuestionDetail.questionType) }}
            </el-tag>
            <span class="exam-tag">
              <el-icon><Tickets /></el-icon>
              试卷类型: {{ currentQuestionDetail.examType }}
            </span>
          </div>
        </div>
        
        <div class="question-content">
          <div class="content-title">题目内容:</div>
          <div class="content-text" v-html="formatQuestionContent(currentQuestionDetail.content)"></div>
        </div>
        
        <div class="correct-answer">
          <div class="section-title">正确答案:</div>
          <div class="section-content" v-html="formatQuestionContent(currentQuestionDetail.correctAnswer)"></div>
        </div>
        
        <div class="analysis-section">
          <div class="section-title">题目解析:</div>
          <div class="section-content" v-html="formatQuestionContent(currentQuestionDetail.analysis)"></div>
        </div>
        
        <div class="knowledge-section">
          <div class="section-title">关联知识点:</div>
          <div class="section-content">
            <el-tag 
              v-for="point in currentQuestionDetail.pointNames.split(', ')" 
              :key="point" 
              type="info"
              style="margin-right: 8px; margin-bottom: 8px">
              {{ point }}
            </el-tag>
          </div>
        </div>
      </div>
      
      <div v-else class="no-detail">
        <el-icon><DocumentDelete /></el-icon>
        <p>暂无详情数据</p>
      </div>
      
      <template #footer>
        <el-button class="custom-reset-button" @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { User, Connection, Tickets, DocumentDelete, Collection } from '@element-plus/icons-vue'
import katex from 'katex'
import MarkdownIt from 'markdown-it'
import markdownItKatex from 'markdown-it-katex'

export default {
  components: {
    User,
    Connection,
    Tickets,
    DocumentDelete,
    Collection
  },
  setup() {
    // 配置markdown-it和KaTeX
    const md = new MarkdownIt({
      html: true,        // 允许HTML标签
      breaks: true,      // 转换换行符
      linkify: true      // 自动转换链接
    }).use(markdownItKatex, {
      // KaTeX配置选项
      throwOnError: false,
      errorColor: '#cc0000',
      strict: false,
      trust: true,
      output: 'html'
    });

    // 状态定义
    const searchInput = ref('')
    const selectedUser = ref(null)
    const isLoading = ref(false)
    const subjects = ref([
      { id: 0, name: '全部科目' },
      { id: 1, name: '高等数学' },
      { id: 2, name: '线性代数' },
      { id: 3, name: '概率论与数理统计' }
    ])
    const selectedSubject = ref(0)
    const collectedQuestions = ref([])
    const currentPage = ref(1)
    const pageSize = ref(5)
    const totalCollectedQuestions = ref(0)
    const isLoadingQuestions = ref(false)
    
    // 题目详情相关状态
    const detailDialogVisible = ref(false)
    const currentQuestionDetail = ref(null)
    const isDetailLoading = ref(false)

    // 题目类型映射
    const questionTypeMap = {
      'single_choice': '单选题',
      'fill_in_the_blank': '填空题',
      'subjective': '主观题'
    }

    // 格式化题目类型
    const formatQuestionType = (type) => {
      return questionTypeMap[type] || type
    }

    // 获取题目类型对应的标签样式
    const getQuestionTypeTag = (type) => {
      const typeMap = {
        'single_choice': 'primary',
        'fill_in_the_blank': 'warning',
        'subjective': 'success'
      }
      return typeMap[type] || 'info'
    }
    
    // 格式化题目内容 - 使用KaTeX和markdown-it处理
    const formatQuestionContent = (content) => {
      if (!content) return '';
      
      try {
        // 预处理内容
        let processedContent = content
          .replace(/\\n/g, '\n')  // 处理换行符
          .replace(/\\\$/g, '###DOLLAR###')  // 临时替换转义的美元符号
          .replace(/\$\$([^$]+)\$\$/g, (match, formula) => {
            // 处理块级数学公式 $$...$$
            try {
              return katex.renderToString(formula.trim(), {
                displayMode: true,
                throwOnError: false,
                strict: false,
                trust: true
              });
            } catch (error) {
              console.warn('KaTeX block formula error:', error, 'Formula:', formula);
              return `<span class="katex-error">$$${formula}$$</span>`;
            }
          })
          .replace(/\$([^$\n]+)\$/g, (match, formula) => {
            // 处理行内数学公式 $...$
            try {
              return katex.renderToString(formula.trim(), {
                displayMode: false,
                throwOnError: false,
                strict: false,
                trust: true
              });
            } catch (error) {
              console.warn('KaTeX inline formula error:', error, 'Formula:', formula);
              return `<span class="katex-error">$${formula}$</span>`;
            }
          })
          .replace(/###DOLLAR###/g, '$');  // 恢复转义的美元符号
        
        // 使用markdown-it处理其他格式
        const htmlContent = md.render(processedContent);
        
        return htmlContent;
      } catch (error) {
        console.error('formatQuestionContent error:', error);
        return content.replace(/\\n/g, '<br>');
      }
    };
    
    // 截取内容方法 - 改进版，先渲染公式再截取
    const truncateContent = (content) => {
      if (!content) return '';
      
      // 先渲染完整内容
      const renderedContent = formatQuestionContent(content);
      
      // 创建一个临时DOM元素来操作内容
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = renderedContent;
      
      // 移除所有HTML标签，只保留文本内容（包括KaTeX渲染后的内容）
      const textContent = tempDiv.textContent || tempDiv.innerText || '';
      
      // 截取前40个字符
      if (textContent.length <= 40) {
        return renderedContent;
      }
      
      // 创建一个新的临时元素来存储截取后的内容
      const truncatedDiv = document.createElement('div');
      truncatedDiv.innerHTML = renderedContent;
      
      // 遍历所有节点，保留前40个字符的内容
      let totalLength = 0;
      const walker = document.createTreeWalker(
        truncatedDiv,
        NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
        null,
        false
      );
      
      let node;
      while ((node = walker.nextNode())) {
        if (node.nodeType === Node.TEXT_NODE) {
          const remaining = 40 - totalLength;
          if (remaining <= 0) {
            node.nodeValue = '';
            continue;
          }
          
          if (node.nodeValue.length > remaining) {
            node.nodeValue = node.nodeValue.substring(0, remaining) + '...';
            totalLength = 40;
          } else {
            totalLength += node.nodeValue.length;
          }
        }
      }
      
      // 移除超出部分的元素
      for (let i = 0; i < truncatedDiv.children.length; i++) {
        const child = truncatedDiv.children[i];
        if (child.textContent.trim() === '') {
          child.remove();
          i--;
        }
      }
      
      return truncatedDiv.innerHTML;
    }

    // 用户搜索
    const handleSearch = async () => {
      if (!searchInput.value.trim()) {
        ElMessage.warning('请输入用户名');
        return;
      }

      isLoading.value = true;
      try {
        const response = await axios.get('/api/questions/collected/searchUser', {
          params: { username: searchInput.value.trim() }
        });

        selectedUser.value = {
          userId: response.data.userId,
          username: response.data.username
        };
        ElMessage.success(`找到用户: ${response.data.username}`);
        loadCollectedQuestions();
      } catch (error) {
        console.error('搜索用户失败:', error);
        if (error.response?.status === 404) {
          ElMessage.error('用户不存在，请检查用户名是否正确');
        } else {
          ElMessage.error('搜索用户失败: ' + (error.response?.data?.message || error.message));
        }
        selectedUser.value = null;
      } finally {
        isLoading.value = false;
      }
    };

    // 清除搜索
    const clearSearch = () => {
      searchInput.value = ''
      selectedUser.value = null
      collectedQuestions.value = []
      totalCollectedQuestions.value = 0
      currentPage.value = 1
      selectedSubject.value = 0
    }

    // 处理每页条数变化
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      currentPage.value = 1
      loadCollectedQuestions()
    }

    // 加载收藏题目
    const loadCollectedQuestions = async () => {
      if (!selectedUser.value) return

      isLoadingQuestions.value = true
      try {
        const params = {
          userId: selectedUser.value.userId,
          subjectId: selectedSubject.value === 0 ? null : selectedSubject.value,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }

        // 调用后端收藏题目接口
        const response = await axios.get('/api/questions/collected', {
          params,
          paramsSerializer: params => {
            return Object.keys(params)
              .filter(key => params[key] !== null)
              .map(key => `${key}=${params[key]}`)
              .join('&')
          }
        })

        collectedQuestions.value = response.data.list
        totalCollectedQuestions.value = response.data.total
      } catch (error) {
        console.error('加载收藏题目失败:', error)
        ElMessage.error('加载收藏题目失败: ' + (error.response?.data?.message || error.message))
      } finally {
        isLoadingQuestions.value = false
      }
    }
    
    // 查看题目详情
    const viewQuestionDetail = async (questionId) => {
      if (!selectedUser.value) return
      
      isDetailLoading.value = true
      try {
        // 模拟获取题目详情
        currentQuestionDetail.value = {
          questionId: questionId,
          content: collectedQuestions.value.find(q => q.questionId === questionId)?.content || '题目内容',
          questionType: collectedQuestions.value.find(q => q.questionId === questionId)?.questionType || 'single_choice',
          subjectName: collectedQuestions.value.find(q => q.questionId === questionId)?.subjectName || '高等数学',
          chapterName: collectedQuestions.value.find(q => q.questionId === questionId)?.chapterName || '第一章',
          examType: collectedQuestions.value.find(q => q.questionId === questionId)?.examType || '模拟考试',
          pointNames: collectedQuestions.value.find(q => q.questionId === questionId)?.pointNames || '极限, 导数',
          correctAnswer: collectedQuestions.value.find(q => q.questionId === questionId)?.correctAnswer || '正确答案',
          analysis: collectedQuestions.value.find(q => q.questionId === questionId)?.analysis || '题目解析内容'
        }
        detailDialogVisible.value = true
      } catch (error) {
        console.error('获取题目详情失败:', error)
        ElMessage.error(`获取题目详情失败: ${error.response?.data?.message || error.message}`)
      } finally {
        isDetailLoading.value = false
      }
    }
    
    // 确认筛选
    const handleConfirmFilter = () => {
      if (!selectedUser.value) {
        ElMessage.warning('请先选择用户')
        return
      }
      
      currentPage.value = 1
      loadCollectedQuestions()
    }

    return {
      searchInput,
      selectedUser,
      subjects,
      selectedSubject,
      collectedQuestions,
      currentPage,
      pageSize,
      totalCollectedQuestions,
      isLoading,
      isLoadingQuestions,
      detailDialogVisible,
      currentQuestionDetail,
      isDetailLoading,
      handleSearch,
      clearSearch,
      handleConfirmFilter,
      handleSizeChange,
      loadCollectedQuestions,
      viewQuestionDetail,
      formatQuestionType,
      getQuestionTypeTag,
      truncateContent,
      formatQuestionContent
    }
  }
}
</script>

<style scoped>
/* 整体布局 */
.learning-data-analysis {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header-container {
  position: relative;
  margin-bottom: 30px;
}

.main-title {
  color: #1a2f54;
  font-weight: 600;
  font-size: 24px;
  margin-bottom: 10px;
}

.title-line {
  width: 50px;
  height: 4px;
  background: linear-gradient(90deg, #3b527a, #4e6694);
  border-radius: 2px;
}

/* 卡片通用样式 */
.filter-card, .collected-questions-card {
  border-radius: 10px;
  margin-bottom: 24px;
  border: none;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.filter-card {
  padding: 20px;
}

.filter-bar {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.search-section {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px dashed #e6e9ed;
}

.user-search {
  display: flex;
  gap: 12px;
  align-items: center;
}

.custom-primary-button {
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  border: none;
  color: white;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(26, 47, 84, 0.3);
}

.custom-primary-button:hover {
  background: linear-gradient(135deg, #3b527a 0%, #4e6694 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(26, 47, 84, 0.4);
}

.custom-reset-button {
  background: #f0f2f5;
  border-color: #dcdfe6;
  color: #606266;
  transition: all 0.3s;
}

.custom-reset-button:hover {
  background: #e4e7ed;
  color: #1a2f54;
}

.user-details {
  display: flex;
  gap: 25px;
  font-size: 15px;
  color: #606266;
}

.user-details .highlight {
  font-weight: 600;
  color: #1a2f54;
}

.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.subject-filter {
  display: flex;
  gap: 10px;
  align-items: center;
}

.filter-label {
  font-weight: 500;
  color: #1a2f54;
}

/* 收藏列表卡片 */
.collected-questions-card {
  padding: 0;
}

.overview-header {
  position: relative;
  padding: 16px 20px;
  margin-bottom: 15px;
}

.overview-header h3 {
  color: white;
  position: relative;
  z-index: 2;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  z-index: 1;
}

.collected-questions-list {
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.collection-item {
  padding: 18px;
  background: white;
  border-radius: 8px;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border-left: 3px solid #67c23a;
  cursor: pointer;
}

.collection-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  border-left-color: #4e6694;
}

.question-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  color: #1a2f54;
  line-height: 1.5;
}

.question-id {
  display: inline-block;
  background: #f0f5ff;
  color: #4e6694;
  padding: 2px 8px;
  border-radius: 4px;
  margin-right: 8px;
  font-size: 14px;
}

.question-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 12px;
  font-size: 14px;
  color: #606266;
  flex-wrap: wrap;
  align-items: center;
}

.subject, .chapter {
  background-color: #f0f5ff;
  padding: 4px 10px;
  border-radius: 4px;
  color: #4e6694;
}

.question-details {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  font-size: 13px;
  color: #909399;
}

.question-details > div {
  display: flex;
  align-items: center;
  gap: 6px;
}

.no-data {
  text-align: center;
  padding: 50px 0;
  color: #909399;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.no-data .el-icon {
  font-size: 60px;
  color: #e6e9ed;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-top: 1px solid #ebeef5;
  background: #f9fafc;
}

.total-items {
  font-weight: 500;
  color: #1a2f54;
}

.page-info {
  color: #606266;
  font-size: 14px;
}

/* 题目详情对话框 */
.question-detail {
  padding: 10px;
}

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.detail-header h3 {
  color: #1a2f54;
  font-weight: 600;
  margin-bottom: 15px;
}

.meta-info {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.meta-info > span {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
}

.exam-tag {
  color: #606266;
}

.content-title, .section-title {
  font-weight: bold;
  margin: 15px 0 8px 0;
  color: #1a2f54;
}

.content-text, .section-content {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  line-height: 1.6;
}

.correct-answer .section-content {
  background-color: #f0f9eb;
  color: #67c23a;
  border-left: 3px solid #67c23a;
}

.analysis-section .section-content {
  background-color: #f0f5ff;
  border-left: 3px solid #4e6694;
}

.knowledge-section .section-content {
  background: transparent;
  padding: 10px 0;
}

.no-detail {
  text-align: center;
  padding: 50px 0;
  color: #909399;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.no-detail .el-icon {
  font-size: 60px;
  color: #e6e9ed;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .filter-section {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .subject-filter {
    width: 100%;
  }
  
  .user-search {
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .pagination {
    flex-direction: column;
    gap: 15px;
  }
  
  .user-details {
    flex-direction: column;
    gap: 8px;
  }
}

/* KaTeX全局样式优化 */
:deep(.katex) {
  overflow-x: auto;
  overflow-y: hidden;
  max-width: 100%;
}

:deep(.katex-display) {
  overflow-x: auto;
  overflow-y: hidden;
  padding: 0.5em 0;
}

/* 确保KaTeX在所有容器中都能正确显示 */
:deep(.katex .mord),
:deep(.katex .mrel),
:deep(.katex .mop),
:deep(.katex .mbin),
:deep(.katex .mpunct),
:deep(.katex .mopen),
:deep(.katex .mclose) {
  color: inherit;
}

/* KaTeX错误样式 */
:deep(.katex-error) {
  color: #d32f2f;
  background: #ffebee;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

/* 题目内容中的数学公式样式 */
.question-title :deep(.katex) {
  font-size: 1em;
  line-height: 1.5;
}

.question-title :deep(.katex-display) {
  margin: 0.5em 0;
  text-align: left;
  display: inline;
}
</style>